package com.bestvike.stone.spring.trace.rest;

import com.bestvike.stone.core.lang.ThrowableUtils;
import com.bestvike.stone.spring.client.ClientRequestWrapper;
import com.bestvike.stone.spring.client.ClientResponseWrapper;
import lombok.extern.apachecommons.CommonsLog;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by 许崇雷 on 2017-10-14.
 */
@CommonsLog
public final class OutgoingLog {
    public static Map<String, Object> writeBeginLog(ClientRequestWrapper request) throws IOException {
        String method = request.getMethod().name().toUpperCase();
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("method", method);
        map.put("requestUri", request.getURI().toString());
        map.put("requestHeaders", RestLogUtils.getHeaders(request));
        map.put("requestPath", request.getURI().getPath());
        map.put("requestQuery", request.getURI().getRawQuery());
        map.put("requestParams", RestLogUtils.getParams(request));
        if (method.equals("POST") || method.equals("PUT"))
            map.put("requestBody", RestLogUtils.getBody(request));
        return map;
    }

    public static void writeEndLog(Map<String, Object> map, ClientResponseWrapper response, long tookMs) throws IOException {
        map.put("responseStatus", response.getRawStatusCode());
        map.put("responseHeaders", RestLogUtils.getHeaders(response));
        map.put("responseBody", RestLogUtils.getBody(response));
        map.put("took", tookMs);
        log.info("==>Call Rest: " + map);
    }

    public static void writeErrorLog(Map<String, Object> map, Exception e, long tookMs) {
        map.put("error", ThrowableUtils.getMessage(e));
        map.put("took", tookMs);
        log.error("==>Call Rest Error: " + map);
    }
}
